package com.ebookstore.struts.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.ebookstore.dto.UserInfo;
import com.ebookstore.struts.form.LoginForm;

public class LoginAction extends BaseAction {

  /**
   * 方法实现的功能 : 登录系统
   */
  public ActionForward login(ActionMapping mapping, ActionForm form,
      HttpServletRequest request, HttpServletResponse response) {
	  System.out.println("loginaction.login()");
    request.getSession().removeAttribute("loginUser");
    LoginForm loginForm = (LoginForm) form;
    //调用业务，查询用户名和密码是否匹配
    List list = getEBookStore().getUserService().findUserByNameandPwd(loginForm.getUserName(),
        loginForm.getPassword());
    //获得用户信息
    UserInfo user = null;
    System.out.println("loginaction.login():用户名密码"+loginForm.getUserName()+" "+loginForm.getPassword()
    		+" 是否匹配："+(list==null));
    if (list==null||list.size() == 0) {
      request.setAttribute("message", "登录失败！无效的用户名和密码.");
      return mapping.findForward("failure");
    }
    else {
      user = (UserInfo) list.get(0);  
    }
    //设置用户信息
    request.getSession().setAttribute("loginUser", user);
    
    return mapping.findForward("success");
  }

  /**
   * 方法实现的功能 : 退出系统
   */
  public ActionForward logoff(ActionMapping mapping, ActionForm form,
      HttpServletRequest request, HttpServletResponse response) {
	//清空Session
	  System.out.println("loginaction.logoff()");
    request.getSession().invalidate();
    return mapping.findForward("success");
  }

  /**
   * 方法实现的功能 : 跳转到登录界面
   */
  public ActionForward forward(ActionMapping mapping, ActionForm form,
      HttpServletRequest request, HttpServletResponse response) {
	  System.out.println("loginaction.forward()");
    return mapping.findForward("login");
  }
}
